package com.ymq.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ymq.reggie.common.CoustomExeception;
import com.ymq.reggie.dto.SetmealDto;
import com.ymq.reggie.entity.Setmeal;
import com.ymq.reggie.entity.SetmealDish;
import com.ymq.reggie.mapper.SetmealMapping;
import com.ymq.reggie.service.SetmealDishService;
import com.ymq.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Slf4j
public class SetmealServiceImpl extends ServiceImpl<SetmealMapping, Setmeal> implements SetmealService {
    @Autowired
    private SetmealDishService setmealDishService;
   @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        this.save(setmealDto);

        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
       setmealDishes.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
       log.info("保存到setmeal-dish");

       setmealDishService.saveBatch(setmealDishes);

    }

    @Override
    public void deleteWithDish(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(Setmeal::getId,ids);
        lambdaQueryWrapper.eq(Setmeal::getStatus,"1");
        int count = super.count(lambdaQueryWrapper);
        if(count>0){
           throw  new CoustomExeception("改套餐正在售卖，不能删除");
        }
        //删除setmeal中数据
        super.removeByIds(ids);
        //删除setmeal_dish中数据
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(queryWrapper);

    }
}
